//
//  ViewController.m
//  CoreDataDemo
//
//  Created by UniHan_iMac on 17/4/1.
//  Copyright © 2017年 UniHan_iMac. All rights reserved.
//

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "AppDelegate.h"
#import "People+CoreDataClass.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 获取管理数据上下文
    id appDelegate = [[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *objectContext = [appDelegate  managedObjectContext];
    
    // TODO:插入数据
    // 获取插入数据模型
    NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:objectContext];
    // KVC 给属性赋值
    [object setValue:@"张雨薇" forKey:@"name"];
    [object setValue:@(23) forKey:@"age"];
    [object setValue:@"女" forKey:@"sex"];
    
    People *people = [NSEntityDescription insertNewObjectForEntityForName:@"People" inManagedObjectContext:objectContext];
    people.name = @"张雨薇";
    people.age = 23;
    people.sex = @"女";
    // 保存数据
    [appDelegate saveContext];
    
    // 获取表中的数据(增删改查)
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"People"];
    
    // TODO:更新数据
    // 设置查询条件(谓词)
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name like %@",@"张*"]];
    // 遍历数组,更新数据
    NSArray *updateArray = [objectContext executeFetchRequest:fetchRequest error:nil];
    for (NSManagedObject *object in updateArray) {
        [object setValue:@(24) forKey:@"age"];
    }
    // 保存数据:错误信息为空，更新成功
    if([objectContext save:nil]){
        NSLog(@"更新成功");
    }
    
    // TODO:删除数据
    // 设置查询条件(谓词)
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"name=%@",@"张雨薇"]];
    // 遍历数组,删除数据
    NSArray *deleteArray = [objectContext executeFetchRequest:fetchRequest error:nil];
    for (NSManagedObject *object in deleteArray) {
        [objectContext deleteObject:object];
    }
    // 保存数据:错误信息为空，删除成功
    if([objectContext save:nil]){
        NSLog(@"删除成功");
    }
    
    // TODO:查询数据
    // 遍历数组，查询数据
    NSArray *selectArray = [objectContext executeFetchRequest:fetchRequest error:nil];
    for (NSManagedObject *object in selectArray) {
        NSLog(@"%@",[object valueForKey:@"name"]);
        NSLog(@"%@",[object valueForKey:@"age"]);
        NSLog(@"%@",[object valueForKey:@"sex"]);
    }
}
@end
